package com.yupi.yupicturebackend.manager.websocket;

import com.yupi.yupicturebackend.manager.websocket.PictureEditHandler;
import com.yupi.yupicturebackend.manager.websocket.WsHandshakeInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import javax.annotation.Resource;

/**
 * 类似于Controller 这样就给客户端提供了ws的连接地址
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Resource
    private PictureEditHandler pictureEditHandler;

    @Resource
    private WsHandshakeInterceptor wsHandshakeInterceptor;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // websocket
        registry.addHandler(pictureEditHandler, "/ws/picture/edit")
                /**
                 * 注册一个拦截器  wsHandshakeInterceptor的 beforeHandshake 方法只会在 WebSocket 连接建立时执行。
                 * 也就是当 WebSocket 连接已经建立成功后，前端通过该连接发送消息时，beforeHandshake 方法不会被触发。
                 */
                .addInterceptors(wsHandshakeInterceptor)
                /**
                 * 允许跨域
                 */
                .setAllowedOrigins("*");
    }
}
